<template>
  <div>
    <!-- <h2>角色管理</h2> -->
    <div class="search">
      <el-card>
        <el-form :inline="true" :model="searchData" class="demo-form-inline">
          <el-form-item label="role name by">
            <el-input v-model="searchData.user" placeholder="role name by" clearable />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSearchSubmit">搜索</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
    <div class="mytable">
      <el-card class="m-b10">
        <el-button type="primary" @click="addItemHandler()">添加</el-button>
      </el-card>
      <el-card>
        <el-table :data="tableData" style="width: 100%">
          <el-table-column fixed prop="id" label="角色ID" width="120" />
          <el-table-column prop="status" label="角色状态" width="120" />
          <el-table-column prop="name" label="角色名称" width="300" />
          <el-table-column prop="code" label="角色编码" width="200" />
          <el-table-column prop="sort" label="排序" width="100" />
          <el-table-column fixed prop="updateTime" label="更新日期" width="200" />
          <el-table-column fixed="right" label="操作" min-width="200">
            <!-- row 是 el-table-column 组件的 template 插槽中提供的一个上下文变量。这个变量代表当前行的数据对象，包含了该行的所有相关信息。 -->
            <template #default="{ row }">
              <el-button link type="primary" size="small" @click="editItemHandler(row)">
                修改
              </el-button>
              <el-button link type="primary" size="small" @click="deleteRole(row.id)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
    <div class="mypage">
      <!-- 分页属性：background - 是否为分页按钮添加背景色-->
      <!-- 分页事件：change - `current-page` 或 `page-size` 更改时触发 -->
      <el-pagination
        background
        layout="prev, pager, next"
        :total="pageParams.total"
        @change="pageChangeHandler"
      />
    </div>

    <!-- 弹框（模态框） -->
    <div class="myModalBox">
      <!-- 对话框（弹出模态框） -->
      <el-dialog v-model="isFormVisible" title="RoleDataForm" width="800">
        <el-form
          ref="ruleFormRef"
          style="max-width: 600px"
          :model="ruleForm"
          :rules="rules"
          label-width="auto"
          class="demo-ruleForm"
          :size="formSize"
          status-icon
        >
          <el-form-item label="角色ID" prop="id">
            <el-input v-model="ruleForm.id" />
          </el-form-item>
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="ruleForm.name" />
          </el-form-item>
          <el-form-item label="角色编码" prop="code">
            <el-input v-model="ruleForm.code" />
          </el-form-item>

          <el-form-item label="角色状态" prop="status">
            <el-switch
              v-model="ruleForm.status"
              inline-prompt
              active-text="启动"
              inactive-text="禁用"
              :active-content="1"
              :inactive-content="0"
            />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" :disabled="isSBtnDisable" @click="submitForm(ruleFormRef)">
              Create
            </el-button>
            <el-button @click="resetForm(ruleFormRef)">Reset</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import {
  type RolesType,
  requestGetRolesPage,
  delRole,
  editRole,
  addRole
} from '@/service/study1/demo3'
import { onMounted, reactive, ref } from 'vue'
import { ElMessage, type ComponentSize, type FormInstance, type FormRules } from 'element-plus'

const tableData = ref<RolesType[]>()

const pageParams = ref({
  pageNum: 1, //当前页
  pageSize: 15, //每页数量
  total: 0
})

/**
 * 获取分页数据
 */
const getPageData = async () => {
  const resRoles = await requestGetRolesPage({
    pageNum: pageParams.value.pageNum,
    pageSize: pageParams.value.pageSize,
  })
  console.log(resRoles, 'resRoles')
  tableData.value = resRoles.data.list
  pageParams.value.total = resRoles.data.total
}

/**
 * 分页时间
 */
const pageChangeHandler = (currentPage: number, pageSize: number) => {
  pageParams.value.pageNum = currentPage
  pageParams.value.pageSize = pageSize
  getPageData()
}

/**
 * 删除角色
 */
const deleteRole = (ids: string) => {
  delRole(ids)
  getPageData()
}

/**
 * 修改角色
 */
const changeRole = (roleId: number, data: RolesType) => {
  editRole(roleId, data)
}

/**
 * 挂载完成时获取数据
 */
onMounted(() => {
  getPageData()
})

/**
 * 弹框
 */
const formSize = ref<ComponentSize>('default')
const ruleFormRef = ref<FormInstance>()
const ruleForm = ref<RolesType>({
  createTime: '',
  status: 1,
  name: '',
  code: '',
  sort: 1
})

const ruleFormInfo = ref<{ type: 'add' | 'edit'; title: string }>({
  type: 'add',
  title: '添加数据'
})

const isFormVisible = ref(false)
const isSBtnDisable = ref(false)
// 校验规则  [ trigger: 'blur' - 失去焦点时触发验证 ]
const rules = reactive<FormRules<RolesType>>({
  id: [{ required: true, message: '不可以为空', trigger: 'blur' }],
  name: [{ required: true, message: '不可以为空', trigger: 'blur' }],
  code: [{ required: true, message: '不可以为空', trigger: 'blur' }],
  status: [{ required: true, message: '不可以为空', trigger: 'blur' }]
})

const submitForm = async (formEl: FormInstance | undefined) => {
  isSBtnDisable.value = true
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      ruleForm.value.id = Number(ruleForm.value.id)
      // 添加数据
      if (ruleFormInfo.value.type === 'add') {
        // http 请求
        const res = await addRole(ruleForm.value)
        if (res.code !== '2000') {
          ElMessage.error('数据添加失败')
          return
        }
        ElMessage.error('数据添加成功')
      }
      // 修改数据
      if (ruleFormInfo.value.type === 'edit') {
        // http 请求
        const res = await editRole(ruleForm.value.id, ruleForm.value)
        if (res.code !== '2000') {
          ElMessage.error('数据添加失败')
          return
        }
        ElMessage.error('数据添加成功')
      }

      isSBtnDisable.value = false
      // 关闭模态框
      isFormVisible.value = false
      // 重新获取数据
      getPageData()
      // 重置表单
      formEl.resetFields()
    } else {
      console.log('error submit!', fields)
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

/**
 * 添加数据
 */
const addItemHandler = () => {
  ruleFormInfo.value = {
    type: 'add',
    title: '添加角色'
  }
  // 清空验证
  ruleFormRef.value?.clearValidate()
  // 重置表单
  ruleFormRef.value?.resetFields()
  isFormVisible.value = true
}

/**
 * 修改数据
 */
const editItemHandler = (row: RolesType) => {
  ruleFormInfo.value = {
    type: 'edit',
    title: '修改角色'
  }
  ruleForm.value = row
  isFormVisible.value = true

  onMounted(() => {
    getPageData()
  })
}

/**
 * 搜索功能实现
 */
 const searchData = reactive({
  user: ''
})
const onSearchSubmit = async () => {
  pageParams.value.pageNum = 1; // 重置为第一页
  await getPageData1(searchData);
}
const getPageData1 = async (searchData:any) => {
  const resRoles = await requestGetRolesPage({
    pageNum: pageParams.value.pageNum,
    pageSize: pageParams.value.pageSize,
    name: searchData.name // 传递角色名称作为搜索条件
  })
  console.log(resRoles, 'resRoles')
  tableData.value = resRoles.data.list
  pageParams.value.total = resRoles.data.total
}
//  const searchData = reactive({
//   user: '',
//   region: '',
//   date: ''
// })

// const onSearchSubmit = () => {
//   console.log('submit!')
// }
</script>

<style scoped>
.mytable {
  margin: 10px 0;
}
.mypage {
  margin-bottom: 10px;
}
.m-b {
  margin-bottom: 10px;
}
</style>
